package page;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import ressource.Achat;

/**
 * Servlet implementation class MesAchatsServlet
 */
public class MesAchatsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MesAchatsServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher dis;
		Connection con = null;
		ServletContext context = getServletContext();
		
		//Si je ne suis pas connecte, je suis redirige
		Integer membre = (Integer)session.getAttribute("user_id");
		if(membre == null){
			dis = request.getRequestDispatcher("/login.jsp");
			dis.forward(request, response);
			return;
		}
		
		try{
			Context namingContext;
			PreparedStatement pstmt;
			ResultSet rs;
			List<Achat> achats = new ArrayList<Achat>();
			Achat a;
			
			namingContext = new InitialContext();
			DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
			con = dataSource.getConnection();
			
			//Recuperation du nombre de resultats pour la requete
			StringBuilder sb = new StringBuilder();
			sb.append("SELECT COUNT(*) AS nb_results FROM `produit` p, `annonce` a, `vente` v, `membre` m WHERE v.id_annonce=a.id_annonce AND a.id_produit=p.id_produit AND m.id_membre=a.id_vendeur AND v.id_acheteur=?");
			String action = request.getParameter("action");
			if(action !=null && action.equals("encours")){
				sb.append(" AND v.note IS NULL");
				request.setAttribute("action", "encours");
			}else{
				sb.append(" AND v.note IS NOT NULL");
			}
			pstmt = con.prepareStatement(sb.toString()); 
			pstmt.setInt(1, membre);
			
			Integer nb_results = 0;
			rs = pstmt.executeQuery();
			if(rs.next()){
				nb_results = rs.getInt("nb_results");
				rs.close();
			}
			
			//Recuperation des achats du membre
			sb = new StringBuilder();
			sb.append("SELECT v.id_vente, v.id_acheteur, a.id_vendeur, m.pseudo, v.note, v.commentaire, v.stock, v.date, p.intitule, p.photo,  a.etat, v.prix FROM `produit` p, `annonce` a, `vente` v, `membre` m WHERE v.id_annonce=a.id_annonce AND a.id_produit=p.id_produit AND m.id_membre=a.id_vendeur AND v.id_acheteur=?");
			if(action !=null && action.equals("encours")){
				sb.append(" AND v.note IS NULL");
				request.setAttribute("action", "encours");
			}else{
				sb.append(" AND v.note IS NOT NULL");
			}
			sb.append(" ORDER BY v.date");
			sb.append(" LIMIT ?, ?");
			pstmt = con.prepareStatement(sb.toString());
			pstmt.setInt(1, membre);

			//On gere la pagination :
			Integer resultspage = 20;
			Integer i=0;
			try{
				resultspage = Integer.parseInt(context.getAttribute("nbresults").toString());
				if(request.getParameter("page") != null)
					i = Integer.parseInt(request.getParameter("page")) - 1;
			}catch(NumberFormatException e){
				i = 0;
			}
			if(i < nb_results / resultspage ) {
				int buff = i * resultspage;
				pstmt.setInt(2, buff);
				pstmt.setInt(3, resultspage);
			}
			else{
				pstmt.setInt(2, 0);
				pstmt.setInt(3, resultspage);
			}
			request.setAttribute("nb_results", (int)nb_results/resultspage);
			request.setAttribute("page", i+1);
			
			rs = pstmt.executeQuery();
			while(rs.next()){
				a = new Achat();
				a.setIdVente(rs.getInt("id_vente"));
				a.setIdAcheteur(rs.getInt("id_acheteur"));
				a.setIdVendeur(rs.getInt("id_vendeur"));
				a.setPseudo(rs.getString("pseudo"));
				a.setProduit(rs.getString("intitule"));
				a.setPhoto(rs.getString("photo"));
				a.setNombre(rs.getInt("stock"));
				a.setEtat(rs.getString("etat"));
				a.setPrix(rs.getInt("prix"));
				a.setDate(rs.getTimestamp("date"));
				a.setNote(rs.getFloat("note"));
				a.setCommentaire(rs.getString("commentaire"));
				
				achats.add(a);
			}
			
			request.setAttribute("achats", achats);
			
			dis = request.getRequestDispatcher("/mesachats.jsp");
			dis.forward(request, response);
		}catch(NamingException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect("profile");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect("profile");
		} finally {
			try {
				if(con != null) con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
